class Command < ActiveRecord::Base
  def after_create
    
    user = User.find_by_phone(phone_number)
    type = type_of(body)
    
    case type
      when 'login'
        re = /(login)\s(\w*)/
        md = re.match(body)
        identifier = md[2] unless md.nil?
     
        # 1) Cancel previous active presence
        user.presences.last.cancel unless user.presences.empty?
        # 2) Establish new presence
        user.presences.create({:identifier => identifier, :status => '1'}) 
        # Continued in PresenceObserver
        
        logger.info("#{user.login} login from #{identifier}")
        user.activities.create(:body => "logging in from #{identifier}")
   
      when 'whoishere'
        logger.info("#{user.login} gets buddy roster")
    
      when 'logout'
        if (user.presences.last.active?) 
          user.presences.last.cancel
          logger.info("#{user.login} logs out")
          user.activities.create(:body => "logging out")        
        end  

      when 'met'
       re = /(met)\s(\w*)/
       md = re.match(body)
       rcp = md[2] unless md.nil?

       met = User.find_by_identity(rcp)
       user.activities.create(:body => "met #{met.login}")
       met.activities.create(:body => "met #{user.login}")  
       
       logger.info("#{user.login} meets #{met.login}")
       
    
      when 'ping'
        re = /(ping)\s(\w*)\s(.*)/
        md = re.match(body)
        rcp = md[2]
        body = md[3]
        
        recipient = User.find_by_identity(rcp)
        aka = user.aka(recipient.service)
                
        unless (user.online?)
          Notifier.deliver_report_tried_to_ping_while_offline(user)
        else
          unless recipient
            Notifier.deliver_report_tried_to_ping_unknown_user(user,recipient)
          else 
            unless (recipient.online? and User.coexist?(user,recipient))
              Ping.store(user.id, recipient.id, body, user.latest_known_location, aka) 
              Notifier.deliver_report_tried_to_ping_invalid_recipient(user, rcp)
            else
              user.sent_pings.create(:recipient_id => recipient.id, :body => body)
              Notifier.deliver_report_got_ping(recipient, user, body, aka)
            end
          end
        end

        logger.info("#{user.login} pings #{rcp}: #{body}")
        user.activities.create(:body => "pinging #{rcp}: #{body}")
        recipient.activities.create(:body => "got ping from #{aka}: #{body}")        
    end 
    
  end
  
  protected
  
  def validate_on_create
    errors.add(:msg, 'Unrecognized message') unless type_of(body)
  end
  
  def type_of(body)
    
    type = body
    body.downcase!
    
    type = 'login'  if body.match('login')
    type = 'logout' if body.match('logout')
    type = 'ping'   if body.match('ping')
    type = 'met'    if body.match('met')


    type
    
  end
end
